package indi.zhifa.study2025.test.rabbitmq.ps.consumer.handler;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;

import indi.zhifa.engine.core.common.entity.web.RestResponse;
import indi.zhifa.engine.core.common.entity.web.ServiceException;
import indi.zhifa.study2025.test.rabbitmq.common.Constant;
import indi.zhifa.study2025.test.rabbitmq.common.entity.FabRequest;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQListener {

    @RabbitListener(queues = Constant.PQ_QUE_NAME1)
    public void queue1ReceiveMessage(String message) {
        System.out.println("que1 Received message: " + message);
    }

    @RabbitListener(queues = Constant.PQ_QUE_NAME2)
    public void queue2ReceiveMessage(String message) {
        System.out.println("que2 Received message: " + message);
    }

    public Double fab(FabRequest PFabRequest) {
        Double a1 = PFabRequest.getA1();
        Double a2 = PFabRequest.getA2();
        if(PFabRequest.getN() <= 0){
            throw new ServiceException("n必须是大于0的整数");
        }
        if(PFabRequest.getN() == 1){
            return a1;
        }else if(PFabRequest.getN() == 2){
            return a2;
        }
        Double res = a2;
        for(int i=3;i<PFabRequest.getN();i++){
            res = a1 * PFabRequest.getK1() + a2 * PFabRequest.getK2();
            a1 = a2;
            a2 = res;
        }
        return res;
    }


    @RabbitListener(queues = Constant.PRC_QUE_REQUEST_S1)
    public String fabRbc(Message message, Channel channel) {
        try{
            FabRequest request = JSONObject.parseObject(message.toString(),FabRequest.class);
            Double rsp = fab(request);
            RestResponse<Double> response = RestResponse.<Double>ok(rsp);

            return JSONObject.toJSONString(response);
        }catch (ServiceException ex){
            RestResponse response = RestResponse.error(500,ex.getMessage());
            return JSONObject.toJSONString(response);
        }
    }

}
